package com.haier.npt.gateway.log;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liuzx
 *
 * 2017年12月8日
 */
@WebFilter(filterName = "LogFilter", urlPatterns = "/*")
public class LogFilter implements Filter {
	static String UNKOWN = "unknown";
	static String NULL = "null";
	String gatewayIp;
	Logger visitLogger = LoggerFactory.getLogger("npt_gateway_visit");

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		try {
			Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
			while (interfs.hasMoreElements()) {
				NetworkInterface interf = interfs.nextElement();
				Enumeration<InetAddress> addres = interf.getInetAddresses();
				while (addres.hasMoreElements()) {
					InetAddress in = addres.nextElement();
					if (in instanceof Inet4Address) {
						if (!"127.0.0.1".equals(in.getHostAddress())) {
							gatewayIp = in.getHostAddress();
							return;
						}
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		String url = httpServletRequest.getRequestURI();
		LogEntity entity = new LogEntity();
		entity.setUrl(url);
		entity.setStartTime(new Date());
		entity.setGatewayIp(gatewayIp);
		try {
			entity.setServerName(httpServletRequest.getServerName());
			entity.setClientIp(getIRealIPAddr(httpServletRequest));
			Cookie[] cookies = httpServletRequest.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if ("userName".equals(cookie.getName())) {
						entity.setUserName(cookie.getValue());
						break;
					}
				}
			}
			chain.doFilter(request, response);
		} catch (Exception ex) {
			throw ex;
		} finally {
			entity.setStatus(httpServletResponse.getStatus());
			entity.setConsumeTime((int) (new Date().getTime() - entity.getStartTime().getTime()));
			visitLogger.info(JSON.toJSONString(entity));
			//System.err.println(JSON.toJSONString(entity, true));
		}
	}

	String getIRealIPAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKOWN.equalsIgnoreCase(ip) || NULL.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			if (ip == null || ip.length() == 0 || UNKOWN.equalsIgnoreCase(ip) || NULL.equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
				if (ip == null || ip.length() == 0 || UNKOWN.equalsIgnoreCase(ip) || NULL.equalsIgnoreCase(ip)) {
					ip = request.getRemoteAddr();
				}
			}
		}
		return ip;
	}

	/**
	 * 截取关键字紧跟着的编号
	 * @param url
	 * @param keyWord
	 * @return
	 */
	String handleKeyWords(String url, String keyWord) {
		String substr = StringUtils.substringAfter(url, keyWord);
		String content = StringUtils.substringBefore(substr, "/");
		if (content.matches("\\d+")) {
			return content;
		}
		return null;
	}
}
